package cn.laike.common.utils;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.Stroke;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.imageio.ImageIO;

import cn.laike.modules.dev.entity.ConfigEntity;




public class ImageUtils {

	public static void drawMemberCard(
			String inputFilePath, String outputFilePath) throws Exception {
		int width = 720;
		int height = 450;
		String s = "姓名:" + "张三";
		String s2 = "性别:" + "男";
		String s3 = "积分:" + 10000 / 1000 + "分";
		String s4 = "余额:" + 1000 / 100 + "元";
		String s5 = "暗号:" + "";
		File file = new File(outputFilePath);
		Font font = new Font("宋体", Font.BOLD, 24);

		File input = new File(inputFilePath);
		BufferedImage image = ImageIO.read(input);

		BufferedImage bi = new BufferedImage(width, height,
				BufferedImage.SCALE_DEFAULT);
		Graphics2D g2 = (Graphics2D) bi.getGraphics();

		// g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
		// (RenderingHints.VALUE_TEXT_ANTIALIAS_ON));
		g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
				(RenderingHints.VALUE_TEXT_ANTIALIAS_GASP));

		g2.setBackground(Color.WHITE);
		g2.clearRect(0, 0, width, height);
		g2.setPaint(Color.BLACK);

		//
		// width = image.getWidth() / 5;
		// height = image.getHeight() / 5;
		// // logo起始位置，此目的是为logo居中显示
		// int x = (image.getWidth() - width) / 2;
		// int y = (image.getHeight() - height) / 2;
		// g2.drawImage(logo, x, y, width, height, null);
		//
		g2.drawImage(image, 100, 60, 230, 230, null);
		// g2.setColor(Color.RED);
		// g2.drawString("技术支持:智讯互联", 150, 280);

		//
		// width = image.getWidth() / 5;
		// height = image.getHeight() / 5;
		// // logo起始位置，此目的是为logo居中显示
		// int x = (image.getWidth() - width) / 2;
		// int y = (image.getHeight() - height) / 2;
		// g2.drawImage(logo, x, y, width, height, null);
		//

		// FontRenderContext context = g2.getFontRenderContext();
		// Rectangle2D bounds = font.getStringBounds(s, context);
		// double x = (width - bounds.getWidth()) / 2;
		// double y = (height - bounds.getHeight()) / 2;
		// double ascent = -bounds.getY();
		// double baseY = y + ascent;
		g2.setPaint(Color.BLACK);
		g2.setFont(font);
		int x = 380;
		int y = -20;
		int pading = 20;
		g2.drawString(s, x, 100 + y + pading);

		g2.drawString(s2, x, 140 + y + pading);
		g2.drawString(s3, x, 180 + y + pading);
		g2.drawString(s4, x, 220 + y + pading);
		g2.drawString(s5, x, 260 + y + pading);

		// 画线
		// g2.setColor(Color.RED);
		// g2.drawLine(10, 330, 730, 330);

		ImageIO.write(bi, "png", file);

		g2.dispose();
	}

	/**
	 * 合并图片，并追加文字
	 * 
	 * @param name
	 *            姓名
	 * @param time
	 *            时间
	 * @param backgroundFilePath
	 *            背景图
	 * @param inputFilePath
	 *            封面图
	 * @param outputFilePath
	 *            合成图片
	 * @throws Exception
	 */
	public static void drawImage(String name, String time, String intro,
			String backgroundFilePath, String inputFilePath,
			String outputFilePath) {
		try {
			File file = new File(outputFilePath); // 输出文件路径
			Font font = new Font("迷你简黄草", Font.BOLD, 26);
			Font font1 = new Font("迷你简黄草", Font.BOLD, 22);

			File input = new File(inputFilePath);
			BufferedImage image = ImageIO.read(input);

			File background = new File(backgroundFilePath); // 背景图
			BufferedImage bi = ImageIO.read(background);
			Graphics2D g2 = (Graphics2D) bi.getGraphics();

			g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
					(RenderingHints.VALUE_TEXT_ANTIALIAS_GASP));

			g2.setPaint(Color.BLACK);

			g2.drawImage(image, 42, 327, 350, 595, null);

			g2.setPaint(new Color(213, 90, 58));
			g2.setFont(font);
			System.out.println(name);
			System.out.println(time);

			g2.drawString(name, 540, 770);
			g2.drawString(time, 540, 800);
			//g2.drawString(intro, 540, 800);
			
			
			drawStringMultiLine(g2, intro, 260, 400, 420, 530, font1);

			ImageIO.write(bi, "png", file);

			g2.dispose();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	/**
	 * 
	 * 描述: 长字符串缩小字体自动换行
	 * 
	 * @param g
	 * @param text
	 *            字符串
	 * @param lineWidth
	 *            单元格宽度
	 * 
	 * @param cellHeight
	 *            单元格高度
	 * @param x
	 *            x坐标
	 * @param y
	 *            y坐标
	 * @param cellFont
	 *            原字体
	 */

	public static void drawStringMultiLine(Graphics2D g, String text,
			int lineWidth, int cellHeight, int x, int y, Font cellFont) {
		FontMetrics m = g.getFontMetrics();
		if (m.stringWidth(text) < lineWidth) {
			g.drawString(text, x, y);
		} else {
			/* 使用当前字体, 根据单元格宽度计算出应该打印行数 */
			int strWidth = 0;
			int widthLine = 1;
			char[] chars = text.toCharArray();
			for (int i = 0; i < chars.length; i++) {
				if (m.charWidth(chars[i]) > lineWidth) { // 单个字比单元格宽，肯定缩小字体
					widthLine = 10000;
					break;
				}

				strWidth += m.charWidth(chars[i]);
				if (strWidth > lineWidth) {
					widthLine++;
					strWidth = 0;
					i--;
				}
			}

			String name = "Serif";
			int style = Font.PLAIN;
			int high = 25; // 默认16号字
			Font font = null;
			if (cellFont != null) {
				name = cellFont.getName();
				style = cellFont.getStyle();
				high = cellFont.getSize();
			}
			int fontHeight = m.getAscent() + m.getDescent()+10;	//行间距

			/* 计算能打出全部内容时的最大字体 */
			int heightLine = 2;// 一个单元格只能写2行
			while (widthLine > heightLine) {
				/* 缩小字体，重复计算应该打印行数和允许打印行数 */
				font = new Font(name, style, --high);

				m = g.getFontMetrics(font);

				/* 字体高度 */
				fontHeight = m.getAscent() + m.getDescent();
				if (fontHeight <= 0)
					return;

				strWidth = 0;
				/* 使用当前字体, 根据单元格宽度计算出应该打印行数 */
				widthLine = 1;
				for (int i = 0; i < chars.length; i++) {
					if (m.charWidth(chars[i]) > lineWidth) { // 单个字比单元格宽，肯定缩小字体
						widthLine = 10000;
						break;
					}

					strWidth += m.charWidth(chars[i]);
					if (strWidth > lineWidth) {
						widthLine++;
						strWidth = 0;
						i--;
					}
				}

				/* 使用当前字体时,根据单元格高度计算出允许打印行数 */
				heightLine = 0;
				while ((fontHeight * heightLine) <= cellHeight)
					// 最后一行没有行间距
					heightLine++;
				heightLine--;

				if (widthLine <= heightLine)
					break;
			}

			Font oldFont = g.getFont();
			Stroke oldStroke = g.getStroke();
			g.setFont(font);
			g.setStroke(new BasicStroke(1.0f));

			/* 分行，计算各行文字内容 */
			List<String> rows = new ArrayList<String>();
			int fromIndex = 0;
			strWidth = 0;
			for (int bgn = 0; bgn < text.length();) {// 逐个字符累加计算长度,超过行宽,自动换行
				strWidth += m.charWidth(chars[bgn]);

				if (strWidth > lineWidth) {
					rows.add(text.substring(fromIndex, bgn));

					strWidth = 0;
					fromIndex = bgn;
				} else
					bgn++;
			}

			if (fromIndex < text.length()) // 加上最后一行
				rows.add(text.substring(fromIndex, text.length()));
			String element;
			for (Iterator iter = rows.iterator(); iter.hasNext();) {
				element = (String) iter.next();
				/* 绘制字符串 */
				g.drawString(element, (float) x, (float) (y + m.getAscent()));
				y += fontHeight;
			}
			
			g.setFont(oldFont);
			g.setStroke(oldStroke);
		}
	}
	
	/**
	 * 创建寺庙捐款证书
	 */
	public static String recommend_poster(String name,String content,String qrcode,String backgroundPath){
		try {
			String imgurl = "";
			Font font = new Font("迷你简黄草", Font.BOLD, 26);
			Font font1 = new Font("迷你简黄草", Font.BOLD, 22);

			/*File input = new File(inputFilePath);
			BufferedImage image = ImageIO.read(input);*/
			
			InputStream in = getImageStream(backgroundPath);
			BufferedImage bi = ImageIO.read(in); 
			in.close(); 
			/*File background = new File(backgroundFilePath); // 背景图
			BufferedImage bi = ImageIO.read(background);*/
			Graphics2D g2 = (Graphics2D) bi.getGraphics();

			g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
					(RenderingHints.VALUE_TEXT_ANTIALIAS_GASP));

			g2.setPaint(Color.BLACK);

			//g2.drawImage(image, 42, 327, 350, 595, null);

			g2.setPaint(new Color(213, 90, 58));
			g2.setFont(font);
			//System.out.println(name);
			//System.out.println(time);

			g2.drawString(name, 200, 400);
			//g2.drawString(content, 200, 400);
			//g2.drawString(intro, 540, 800);
			
			
			drawStringMultiLine(g2, content, 260, 400, 420, 530, font1);

			
			//ImageIO.write(bi, "png", file);
			
			ByteArrayOutputStream os = new ByteArrayOutputStream();  
			ImageIO.write(bi, "png", os);  
			InputStream is = new ByteArrayInputStream(os.toByteArray());  
			//imgurl = OSSFactory.build().uploadSuffix(is, ".png");
			System.out.println(imgurl);
			
			os.close();
			g2.dispose();
			System.out.println(1);
			//上传文件
			//String suffix = bi.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
		/*	//保存文件信息
			*/
			return imgurl;
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
	}
	
	/**
     * 获取网络图片流
     * 
     * @param url
     * @return
     */
    public static InputStream getImageStream(String url) {
        try {
            HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
            connection.setReadTimeout(5000);
            connection.setConnectTimeout(5000);
            connection.setRequestMethod("GET");
            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                InputStream inputStream = connection.getInputStream();
                return inputStream;
            }
        } catch (IOException e) {
            System.out.println("获取网络图片出现异常，图片路径为：" + url);
            e.printStackTrace();
        }
        return null;
    }
    
    
    public static String createImage(ConfigEntity config,String qrcode,String name,String content,String backgroundFilePath){
    	try {
			Font font = new Font("fangzhenglianting", 0 , 27);
			Font font1 = new Font("fangzhenglianting", 0, 20);

			/** 生成二维码*/
			BufferedImage image = QRCodeUtil.createImage(qrcode, null, false);

			/*File background = new File(backgroundFilePath); // 背景图
			BufferedImage bi = ImageIO.read(background);*/
			InputStream in = getImageStream(backgroundFilePath);
			BufferedImage bi = ImageIO.read(in); 
			in.close(); 
			Graphics2D g2 = (Graphics2D) bi.getGraphics();

			g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
					(RenderingHints.VALUE_TEXT_ANTIALIAS_GASP));

			g2.setPaint(Color.BLACK);

			//g2.drawImage(image, config.getQrcodex(), config.getQrcodey(), 150, 150, null);
			
			
			System.out.println(name);
			g2.setFont(font);
			g2.setPaint(new Color(43, 17, 0));
			//g2.drawString(name, config.getNamex(), config.getNamey());
			//g2.drawString(time, 540, 800);
			//g2.drawString(intro, 540, 800);
			
			g2.setFont(font1);
			g2.setPaint(new Color(43, 17, 0));
			//drawStringMultiLine(g2, content, 520, 200, config.getContentx(), config.getContenty(), font1);
			//ImageIO.write(bi, "png", file);
			//bi = ImageHepler.resize(bi, 341, 495);
			ByteArrayOutputStream os = new ByteArrayOutputStream();  
			ImageIO.write(bi, "jpg", os);  
			InputStream is = new ByteArrayInputStream(os.toByteArray());  
			
			os.close();
			is.close();

			g2.dispose();
			return FileToBase64.getBase64FromInputStream(is);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
    	
    }
    /**
     * 来客推广海报
     * @param config
     * @param qrcode
     * @param name
     * @param content
     * @param backgroundFilePath
     * @return
     */
    public static String createImage(ConfigEntity config,String qrcode,String backgroundFilePath){
    	try {
			Font font = new Font("fangzhenglianting", 0 , 27);
			Font font1 = new Font("fangzhenglianting", 0, 20);

			/** 生成二维码*/
			BufferedImage image = QRCodeUtil.createImage(qrcode, null, false);

			File background = new File(backgroundFilePath); // 背景图
			BufferedImage bi = ImageIO.read(background);
//			InputStream in = getImageStream(config.getRecommendPic());
//			BufferedImage bi = ImageIO.read(in); 
			//in.close(); 
			Graphics2D g2 = (Graphics2D) bi.getGraphics();

			g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
					(RenderingHints.VALUE_TEXT_ANTIALIAS_GASP));

			g2.setPaint(Color.BLACK);

			g2.drawImage(image, config.getQrcodex(), config.getQrcodey(), 300, 300, null);
			
			
			
			//g2.drawString(name, config.getNamex(), config.getNamey());
			//g2.drawString(time, 540, 800);
			//g2.drawString(intro, 540, 800);
			
//			g2.setFont(font1);
//			g2.setPaint(new Color(43, 17, 0));
			//drawStringMultiLine(g2, content, 520, 200, config.getContentx(), config.getContenty(), font1);
			//ImageIO.write(bi, "png", file);
			//bi = ImageHepler.resize(bi, 341, 495);
			ByteArrayOutputStream os = new ByteArrayOutputStream();  
			ImageIO.write(bi, "jpg", os);  
			InputStream is = new ByteArrayInputStream(os.toByteArray());  
			
			os.close();
			is.close();

			g2.dispose();
			return FileToBase64.getBase64FromInputStream(is);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
    	
    }
    

	public static void main(String[] args) {
		try {
			//http://songbaoss.hbweiyinqing.cn/dev/20190112/54e95844a00f464487c220d1998278d3.jpg
			
			/*String outputPath = "D:\\output.png";
			String backgroundPath = "http://songbaoss.hbweiyinqing.cn/dev/20190112/54e95844a00f464487c220d1998278d3.jpg";
			String inputPath = "D:\\p.png";
			String intro = "看惯风起云落; 听遍百兽争鸣; 走过山山水水; 经历点点滴滴。 彩凤辞旧岁 ，你过得还好吗？ 我在邯郸挺好的。 神犬引春来，用快乐做成笔，用真情做成墨，为犬年纳福添彩。";
			// //
			drawImage("张无忌", "2018.01.24", intro, backgroundPath, inputPath,
					outputPath);*/
			String backgroundPath = "http://songbaoss.hbweiyinqing.cn/dev/20190112/54e95844a00f464487c220d1998278d3.jpg";
			String outputFilePath = "D:\\output.png";
			String content = "善金:100.00元，善号：2314，善时：2018年12月12日52分46秒" + "张三";
			String url = "http://www.baidu.com";
			recommend_poster("张三111", content ,url,backgroundPath);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}

}
